package com.cskaoyan.demo8.servlet;

import com.cskaoyan.demo8.bean.PageParameter;
import com.cskaoyan.demo8.common.CommonServlet;
import com.cskaoyan.demo8.mapper.MarketGoodsMapper;
import com.cskaoyan.demo8.model.MarketGoods;
import com.cskaoyan.demo8.util.JacksonUtil;
import com.cskaoyan.demo8.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * 响应的JSON字符串中文乱码问题解决
 * 之前解决过中文乱码问题：POST请求 中文乱码 → request.getXXXX方法获取到的中文乱码 → request.setCharacterEncoding("UTF-8")
 * response.setCharacterEncoding("utf-8");  × 不能完全解决中文乱码问题
 * 设置content-type这个响应头中的字符集编码 →
 * response.setContentType("application/json;charset=utf-8"); √
 * response.setHeader("Content-Type", "application/json;charset=utf-8"); 同上
 */
@WebServlet("/admin/goods/*")
public class AdminGoodsServlet extends CommonServlet {
    // /admin/goods/list?page=1&limit=20&sort=add_time&order=desc
    public void list(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
        //response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PageParameter pageParameter = PageParameter.init(request.getParameterMap());

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketGoodsMapper goodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);

        List<MarketGoods> goodsList = goodsMapper.selectList(pageParameter);
        sqlSession.close();

        String jsonStr = JacksonUtil.write(goodsList);
        response.getWriter().println(jsonStr);
    }
}

